﻿using System;
using System.Windows.Forms;
using ConfigurationManagement.Administration.Data;
using ConfigurationManagement.Data;
using System.ComponentModel;

namespace ConfigurationManagement.Administration.UI
{
    public partial class ManageProjectsForm : Form
    {
        private readonly ConfigurationManagementDataContext _db = new ConfigurationManagementDataContext();

        public ManageProjectsForm()
        {
            InitializeComponent();
        }

        private void ManageProjectsFormLoad(object sender, EventArgs e)
        {
            ProjectsDataGridView.AutoGenerateColumns = false;
            
// ReSharper disable PossibleNullReferenceException
            ProjectsDataGridView.Columns["ProjectDescription"].DataPropertyName = "ProjectDescription";
// ReSharper restore PossibleNullReferenceException
// ReSharper disable PossibleNullReferenceException
            ProjectsDataGridView.Columns["ProjectName"].DataPropertyName = "ProjectName";
            
// ReSharper restore PossibleNullReferenceException
            ProjectsDataGridView.DataSource = _db.Projects;
// ReSharper disable AssignNullToNotNullAttribute
            ProjectsDataGridView.Sort(ProjectsDataGridView.Columns["ProjectName"], ListSortDirection.Ascending);
// ReSharper restore AssignNullToNotNullAttribute
        }

        private void ProjectsDataGridViewUserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            var project = (Project) e.Row.DataBoundItem;
            if (project.Environments.Count <= 0 && project.Solutions.Count <= 0) return;
            var dr =
                MessageBox.Show(@"The project contains additional information are you sure you want to delete?",
                                @"Delete Project", MessageBoxButtons.YesNo);
            if (dr != DialogResult.Yes)
            {
                e.Cancel = true;
                return;
            }
            foreach (var s in project.Solutions)
            {
                foreach (var setting in s.SolutionSettings)
                {
                    _db.SolutionSettings.DeleteOnSubmit(setting);
                    foreach (var settingValue in setting.SettingValues)
                        _db.SettingValues.DeleteOnSubmit(settingValue);
                }
                _db.Solutions.DeleteOnSubmit(s);
            }


            foreach (var env in project.Environments)
                _db.Environments.DeleteOnSubmit(env);
        }

        private void ManageProjectsFormFormClosing(object sender, FormClosingEventArgs e)
        {
            if (!DataContext.ContainsChanges(_db)) return;
            var dr = MessageBox.Show(@"Changes have been made, would you like to submit them?",
                                              @"Confirm changes", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
                _db.SubmitChanges();
        }
    }
}